package com.guli.order.feignInteceptor;
/*
 * @Author 罗俊
 * @date 2020/11/19 - 8:59 上午
 *
 */

import com.guli.order.interceptor.LoginUserInterceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Slf4j
public class RequestHeaderFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {

        /*
        自己写的没有人家的好用
        HttpServletRequest httpServletRequest = LoginUserInterceptor.REQUEST_THREAD_LOCAL.get();

        String cookie = httpServletRequest.getHeader("Cookie");*/


        /**
         * RequestContextHolder 是一个 request 上下文保持器
         * 只要是同一次请求的同一个线程，其获取到的 requestAttributes 都是一样的
         * 因为 RequestContextHolder 的底层是使用 ThreadLocal 来实现的
         * 注意：多线程调用，将会失效
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 可以强转
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;

        /**
         * 因为没有为每一个线程都设置 RequestContextHolder 的 RequestAttributes，
         * 加个判断，这样没有设置 RequestAttributes 的线程就不需要添加额外的请求头了
         * */
        if(ObjectUtils.isEmpty(servletRequestAttributes)){
            return;
        }

        // 然后获取到 request
        HttpServletRequest request = servletRequestAttributes.getRequest();

        // 获取老请求中的 Cookie
        String cookieFromRequestContextHolder = request.getHeader("Cookie");


        // 为feign远程调用设置请求头
        template.header("Cookie",cookieFromRequestContextHolder);

//        log.info("进行了feign远程调用，进行同步请求头中的cookie = {}",cookieFromRequestContextHolder);
    }
}
